//加载公共样式
require('../../assets/css/index.less')

//加载自己的样式
require('./course.less')

//引入tabbar渲染函数
const renderTabbar = require('../../utils/tabbar')

//导入navbar
const renderNavbar = require('../../utils/navbar')

//导入ajax工具函数
const request = require('../../utils/request')

window.onload = () => {
  //渲染tabbar
  renderTabbar('run')
  //渲染navbar
  renderNavbar('course')

  //服务器地址
  const API = 'http://fitness.h5.itsource.cn:3701'

  //获取dom
  const newCourse = document.querySelector('#newCourse')
  const courseList = document.querySelector('#courseList')

  //获取数据
  function getData() {
    request.get('/api/train/courseList').then(res => {
      //解构数据
      let {errno, data} = res.data
      //判断
      if (errno === 0) {
        //渲染
        render(data)
      }
    })
  }

  //初始化发请求
  getData()

  //渲染函数
  function render(data) {
    console.log('data :>> ', data)
    //最新课程数据
    const data1 = data[0]
    //最新课程html
    let html1 = `
      <h3>最新课程</h3>
        <a href='./course-detail.html?id=${data1.courseId}' class="panel br15 shadow">
          <img class="img" src="${API + data1.imgurl}" alt="" id="img1" />
          <div class="info">
            <div class="name">${data1.name}</div>
            <div class="desc">${data1.desc}</div>
          </div>
        </a>
    `
    //最新课程渲染
    newCourse.innerHTML = html1

    //获取课程列表数据
    const data2 = data.filter((v, i) => i !== 0)
    //列表html
    const html2 = `
      ${data2
        .map(
          v => `
        <a href='./course-detail.html?id=${v.courseId}' class="course-item br15 mt20 shadow">
            <img src="${API + v.imgurl}" alt="" class="img" />
            <div class="info">
              <div class="title">${v.name}</div>
              <div class="desc mt10">${v.desc}</div>
            </div>
          </a>
      `
        )
        .join('')}
    `

    //渲染
    courseList.innerHTML = html2
  }
}
